#include <memory>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <strings.h>
#include "mylog.hpp"
using namespace my_log;
//使用客户端的方式:./udpclient ip port
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        //输入方式错误
        LOG(LogLevel::ERROR)<<"输入方式错误，正确方式为:./udpclient ip port";
        exit(0);
    }
    //创建异端并且绑定
    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd==-1)
    {
        //创建失败
        LOG(LogLevel::ERROR)<<"异端创建失败";
        exit(1);
    }
    struct sockaddr_in s;
    s.sin_family=AF_INET;
    int port=std::stoi(argv[2]);
    s.sin_port=htons(port);
    s.sin_addr.s_addr=inet_addr(argv[1]);
    int bin=bind(sockfd,(struct sockaddr*)&s,sizeof(s));
    while(true)
    {
        //获取要发送的消息
        std::cout << "Please Enter# ";
        std::string input;
        getline(std::cin,input);
        //发消息
        ssize_t send=sendto(sockfd,input.c_str(),input.size(),0,(struct sockaddr*)&s,sizeof(s)); 
        (void)send;
        //收消息
        char buf[1024];
        //新创建一个结构体来接受发送方的信息
        struct sockaddr_in peer;
        socklen_t len=sizeof(peer);
        ssize_t recv=recvfrom(sockfd,buf,sizeof(buf)-1,0,(struct sockaddr*)&peer,&len);
        if(recv>0)//收到消息
        {
            buf[recv]=0;
            std::cout<<buf<<std::endl;
        }
    }
    return 0;
}